﻿using System;
using System.Windows;
using System.Windows.Controls;
using Twitt.Common;

namespace Twitt
{
    public partial class MainPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();

            // Set the data context of the listbox control to the sample data
            DataContext = App.ViewModel;
            Loaded += MainPage_Loaded;
        }

        // Load data for the ViewModel Items
        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (!App.ViewModel.IsDataLoaded)
            {
                App.ViewModel.LoadData();
            }
        }

        private void SettingsButtonClick(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Views/TwitterAuthPage.xaml", UriKind.Relative));
        }
        
        private void TweetButtonClick(object sender, RoutedEventArgs e)
        {
            var tweetPage = new TweetPageData
            {
                Tweet = String.Empty
            };

            // Save the detailpage object which the detailpage will load up
            Helper.SaveSetting(Constants.TweetPageFileName, tweetPage);

            NavigationService.Navigate(new Uri("/Views/TweetPage.xaml", UriKind.Relative));
        }

        private void RefreshButtonClick(object sender, RoutedEventArgs e)
        {
            App.ViewModel.Refresh();
        }

        private void ListBoxSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (((ListBox)sender).SelectedIndex == -1)
                return;

            var selectedItem = (ItemViewModel)((ListBox)sender).SelectedItem;
            if (selectedItem == null)
                return;

            var detailPage = new DetailPageData
            {
                UserDisplayName = selectedItem.DisplayUserName,
                UserName = selectedItem.UserName,
                CreatedDate = selectedItem.CreatedDate,
                Text = selectedItem.TweetText,
                Source = selectedItem.Source,
                Id = selectedItem.Id
            };

            // Save the detailpage object which the detailpage will load up
            Helper.SaveSetting(Constants.DetailPageFileName, detailPage);

            NavigationService.Navigate(new Uri("/Views/DetailPage.xaml", UriKind.Relative));
        }
    }
}